package cn.stylefeng.guns.core.util;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;

public class ImgCut {
	public static boolean cutImg(String scrPath,String targetPath,String fileExt,int x,int y,int width,int height){
		FileInputStream fis = null;
		FileImageInputStream its = null;
		boolean flag = false;
		try {
			//建立文件输入流
			fis = new FileInputStream(scrPath);
			//创建图片的文件流的迭代器
//			Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(fileExt);//只针对JPG
			its = new FileImageInputStream(new File(scrPath));
			Iterator<ImageReader> it = ImageIO.getImageReaders(its);//JPG、PNG、GIF等都支持。 
			ImageReader ir = it.next();
			//获取图片流，建立图片文件的输入流
			ImageInputStream iis = ImageIO.createImageInputStream(fis);
			ir.setInput(iis, true);
			//获取裁剪参数
			ImageReadParam param = ir.getDefaultReadParam();
			//定义裁剪区域
			Rectangle rect = new Rectangle(x, y, width, height);
			param.setSourceRegion(rect);
			BufferedImage bi = ir.read(0,param);
			//保存图片
			flag = ImageIO.write(bi, fileExt, new File(targetPath));
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("图片剪裁失败！");
		}finally{
			if(fis != null){
				try{
					fis.close();
				}catch(IOException e){
					e.printStackTrace();
				}
			}
			if(its != null){
				try{
					its.close();
				}catch(IOException e){
					e.printStackTrace();
				}
			}
		}
		return flag;
	}
	
	public static void main(String[] args) {
		String srcPath = "C:/Users/Administrator/Desktop/imgcut/01.jpg";
		String targetPath = "C:/Users/Administrator/Desktop/imgcut/01_temp.jpg";
		String fileExt = "jpg";//或者png gif等
		File file = new File(srcPath);
		if(file.exists()){
			System.out.println("存在");
		}
		cutImg(srcPath, targetPath,fileExt, 20, 20, 20, 20);
	}
}
